<!-- src/views/video/voice/index.vue -->
<template>
  <div class="voice-container">
    <!-- 统计信息 -->
    <el-card class="mb-4">
      <template #header>
        <div class="statistics-header">
          <span>语音统计</span>
          <el-radio-group v-model="statsView" size="small">
            <el-radio-button label="language">按语言</el-radio-button>
            <el-radio-button label="gender">按性别</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <div class="statistics-content">
        <el-row :gutter="20">
          <el-col :span="8" v-for="(stats, type) in currentStats" :key="type">
            <div class="stats-card">
              <div class="stats-title">{{ getType(type) }}</div>
              <div class="stats-number">{{ stats }}</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 搜索过滤 -->
    <el-card class="mb-4">
      <el-form :model="queryParams" :inline="true">
        <el-form-item label="语言" style="width: 180px">
          <el-select v-model="queryParams.language" placeholder="选择语言" clearable>
            <el-option
                v-for="language in languageOptions"
                :key="language"
                :label="getLanguageLabel(language)"
                :value="language"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="性别" style="width: 180px">
          <el-select v-model="queryParams.gender" placeholder="选择性别" clearable>
            <el-option
                v-for="gender in genderOptions"
                :key="gender"
                :label="getGenderLabel(gender)"
                :value="gender"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 语音列表 -->
    <el-card v-loading="loading">
      <el-table :data="voices" border style="width: 100%">
        <el-table-column prop="name" label="语音名称" min-width="150" />
        <el-table-column prop="language" label="语言" width="120">
          <template #default="scope">
            <el-tag>
              {{getLanguageLabel(scope.row.language)}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="100">
          <template #default="scope">
            <el-tag :type="getGenderType(scope.row.gender)">
              {{ getGenderLabel(scope.row.gender) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="支持功能" width="300">
          <template #default="scope">
            <el-tag
                v-if="scope.row.supportPause"
                class="feature-tag"
                type="success"
            >支持暂停</el-tag>
            <el-tag
                v-if="scope.row.emotionSupport"
                class="feature-tag"
                type="warning"
            >情感支持</el-tag>
            <el-tag
                v-if="scope.row.supportInteractiveAvatar"
                class="feature-tag"
                type="info"
            >支持交互</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
                type="primary"
                link
                @click="handlePreviewVoice(scope.row)"
                :disabled="!scope.row.previewAudio"
            >
              <el-icon><VideoPlay /></el-icon>试听
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 试听音频播放器 -->
    <audio
        ref="audioPlayer"
        :src="currentAudioUrl"
        @ended="handleAudioEnd"
        style="display: none"
    ></audio>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Search, Refresh, VideoPlay } from '@element-plus/icons-vue'
import { useVoiceStore } from '@/stores/video/voice'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { getLanguageLabel, getGenderLabel, getGenderType } from '@/utils/label'
const voiceStore = useVoiceStore()
const { voices, voiceStats, loading } = storeToRefs(voiceStore)
const total = ref(0)

const languageOptions = ["Vietnamese", "Indonesian", "Hindi", "Thai", "Urdu", "Arabic", "English", "Malay", "Portuguese"]
const genderOptions = ["male", "female", "neutral", "unknown"]

// 音频播放状态
const isPlaying = ref(false)

// 查询参数
const queryParams = reactive({
  language: '',
  gender: '',
  pageNum: 1,
  pageSize: 10,
})

// 统计视图
const statsView = ref('language')

// 音频播放器
const audioPlayer = ref(null)
const currentAudioUrl = ref('')

// 分页方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  handleQuery()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  handleQuery()
}

const currentStats = computed(() => {
  if (!voiceStats.value?.byLanguageAndGender) return {}

  if (statsView.value === 'language') {
    return Object.entries(voiceStats.value.byLanguageAndGender).reduce((acc, [language, genders]) => {
      acc[language] = Object.values(genders).reduce((sum, count) => sum + count, 0)
      return acc
    }, {})
  } else {
    return Object.values(voiceStats.value.byLanguageAndGender).reduce((acc, genders) => {
      Object.entries(genders).forEach(([gender, count]) => {
        acc[gender] = (acc[gender] || 0) + count
      })
      return acc
    }, {})
  }
})

const getType = (type) => {
  const lowerCaseGender = type.toLowerCase();

  if (statsView.value === 'language'){
    const languageMap = {
      'vietnamese': '越南语',
      'indonesian': '印尼语',
      'hindi': '印地语',
      'thai': '泰语',
      'urdu': '乌尔都语',
      'arabic': '阿拉伯语',
      'english': '英语',
      'malay': '马来语',
      'portuguese': '葡萄牙语',
    };
    return languageMap[lowerCaseGender] || lowerCaseGender;
  }else {
    const genderMap = {
      'male': '男性',
      'female': '女性',
      'unknown': '未知',
      'neutral': '中性',
    };
    return genderMap[lowerCaseGender] || lowerCaseGender;
  }
};

const handleQuery = async () => {
  await voiceStore.fetchVoices(queryParams)
  total.value = voiceStore.total
}

const resetQuery = () => {
  queryParams.language = ''
  queryParams.gender = ''
  handleQuery()
}

const handlePreviewVoice = async (row) => {
  if (!row.previewAudio) {
    ElMessage.warning('暂无试听音频')
    return
  }

  // 如果当前正在播放，则停止播放
  if (isPlaying.value) {
    stopAudio()
    return
  }

  // 验证音频URL
  if (!isValidAudioUrl(row.previewAudio)) {
    ElMessage.error('无效的音频文件地址')
    return
  }

  try {
    // 设置音频源并播放
    audioPlayer.value.src = row.previewAudio
    await audioPlayer.value.play()
    isPlaying.value = true
  } catch (err) {
    console.error('Audio playback failed:', err)
  }
}

// 停止音频播放
const stopAudio = () => {
  if (audioPlayer.value) {
    audioPlayer.value.pause()
    audioPlayer.value.src = '' // 清除音频源
    isPlaying.value = false
  }
}

// 验证音频URL是否有效
const isValidAudioUrl = (url) => {
  if (!url) return false

  try {
    new URL(url)
    return true
  } catch (e) {
    console.error('Invalid audio URL:', e)
    return false
  }
}

const handleAudioEnd = () => {
  currentAudioUrl.value = ''
}

// 初始化
onMounted(() => {
  handleQuery()
  voiceStore.fetchStats()
})
</script>

<style scoped>
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.voice-container {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 16px;
}

.statistics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.statistics-content {
  min-height: 100px;
}

.stats-card {
  text-align: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.stats-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stats-number {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.feature-tag {
  margin-right: 5px;
}

.audio-playing {
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}
</style>